package com.mindmax.user.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mindmax.user.domain.*;
import com.mindmax.user.service.*;
import com.mindmax.user.vo.TenantUserVo;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 关联租户列表Controller
 *
 * @author cabloy
 * @date 2024-04-02
 */

@DataSource(value = DataSourceType.YT_ADMIN)
@RestController
@RequestMapping("/b/tenantUser")
public class TenantUserController extends BaseController
{

    private static final Logger log = LoggerFactory.getLogger(TenantUserController.class);


    @Autowired
    private ITenantUserService tenantUserService;


    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IAdminUserService adminUserService;


    @Autowired
    private IYtUserRoleService ytUserRoleService;


    @Autowired
    private IYtRoleService ytRoleService;

    /**
     * 查询关联租户列表列表
     */
    @PreAuthorize("@ss.hasPermi('user:tenantUser:list')")
    @GetMapping("/tenant")
    public TableDataInfo getUserByTenantId(Long  tenantId)
    {
        log.info("############### getUserByTenantId:{}", tenantId);
        startPage();
        List<TenantUser> list      = tenantUserService.selectTenantUserListByTenantId(tenantId);
        TableDataInfo    dataTable = getDataTable(list);
        clearPage();

        List<Long> userIds = list.stream().map(TenantUser::getUserId).distinct().collect(Collectors.toList());
        List<AdminUser> userList = adminUserService.selectAdminUserByIds(userIds);
        List<YtRole> ytRoles = ytRoleService.selectYtRoleByTenantId(tenantId);
        if (Collections.isEmpty(ytRoles)) {
            //nop
        } else {
            YtRole ytRole = ytRoles.getFirst();
            List<YtUserRole> ytUserRoles = ytUserRoleService.selectByTenantIdAndRoleId(tenantId, ytRole.getId());
            YtUserRole ytUserRole = ytUserRoles.getFirst();

            for (AdminUser adminUser : userList) {
                Long id = adminUser.getId();
                if (ytUserRole == null) {
                    adminUser.setIsAdmin(false);
                } else {
                    adminUser.setIsAdmin(id.equals(ytUserRole.getUserId()));
                }
            }

        }
            dataTable.setRows(userList);
        return dataTable;

    }




    /**
     * 查询关联租户列表列表
     */
    @PreAuthorize("@ss.hasPermi('user:tenantUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(TenantUser tenantUser)
    {
        startPage();
        List<TenantUser> list      = tenantUserService.selectTenantUserList(tenantUser);
        TableDataInfo    dataTable = getDataTable(list);

        clearPage();

        log.info("_____________ TenantUser:  查询关联租户列表列表, 总计： {}", list.size());

        List<Long> tenantIds = list.stream().map(TenantUser::getTenantId).distinct().collect(Collectors.toList());
        List<Long> userIds = list.stream().map(TenantUser::getUserId).distinct().collect(Collectors.toList());

        List<Tenant>    tenants = tenantService.selectTenantListByIds(tenantIds);
        List<AdminUser> users   = adminUserService.selectAdminUserByIds(userIds);

        log.info("_____________ TenantUser:  查询关联租户列表列表, 租户数量： {}", JSON.toJSONString(tenants));
        log.info("_____________ TenantUser:  查询关联租户列表列表, 用户数量： {}",JSON.toJSONString(users));

        Map<Long, Tenant> tenantId2TenantMap
                = tenants.stream().collect(Collectors.toMap(Tenant::getId, Function.identity()));
        Map<Long, AdminUser> userId2UserMap
                = users.stream().collect(Collectors.toMap(AdminUser::getId, Function.identity()));


        List<TenantUserVo> tenantUserVos = Lists.newArrayList();


        for (TenantUser user : list) {
            TenantUserVo tenantUserVo = new TenantUserVo();
            Tenant tenant = tenantId2TenantMap.get(user.getTenantId());
            BeanUtils.copyProperties(user,tenantUserVo);
            if (tenant != null) {
                tenantUserVo.setTenantName(tenant.getTenantName());
                tenantUserVo.setTenantType(tenant.getTenantType());
                tenantUserVo.setTenantStatus(tenant.getStatus());
            }


            AdminUser adminUser = userId2UserMap.get(user.getUserId());

            if (adminUser != null) {
                tenantUserVo.setUserName(adminUser.getUsername());
                tenantUserVo.setEmail(adminUser.getEmail());
                tenantUserVo.setPhoneNumber(adminUser.getPhoneNumber());
                tenantUserVo.setUserStatus(adminUser.getStatus());
            }

            tenantUserVos.add(tenantUserVo);
        }

        dataTable.setRows(tenantUserVos);

        return dataTable;

    }

    /**
     * 导出关联租户列表列表
     */
    @PreAuthorize("@ss.hasPermi('user:tenantUser:export')")
    @Log(title = "关联租户列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TenantUser tenantUser)
    {
        List<TenantUser> list = tenantUserService.selectTenantUserList(tenantUser);
        ExcelUtil<TenantUser> util = new ExcelUtil<TenantUser>(TenantUser.class);
        util.exportExcel(response, list, "关联租户列表数据");
    }

    /**
     * 获取关联租户列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('user:tenantUser:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tenantUserService.selectTenantUserById(id));
    }

    /**
     * 新增关联租户列表
     */
    @PreAuthorize("@ss.hasPermi('user:tenantUser:add')")
    @Log(title = "关联租户列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TenantUser tenantUser)
    {
        return toAjax(tenantUserService.insertTenantUser(tenantUser));
    }

    /**
     * 修改关联租户列表
     */
    @PreAuthorize("@ss.hasPermi('user:tenantUser:edit')")
    @Log(title = "关联租户列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TenantUser tenantUser)
    {
        return toAjax(tenantUserService.updateTenantUser(tenantUser));
    }

    /**
     * 删除关联租户列表
     */
    @PreAuthorize("@ss.hasPermi('user:tenantUser:remove')")
    @Log(title = "关联租户列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tenantUserService.deleteTenantUserByIds(ids));
    }
}
